package com.ruoyi.api.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.api.domain.ShoppingCart;
import com.ruoyi.api.mapper.ShoppingCartMapper;
import com.ruoyi.api.service.IShoppingCartService;
import com.ruoyi.api.vo.ShoppingCartVo;
import com.ruoyi.api.vo.ShoppingCartsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author 寻觅
 * @since 2025-05-29
**/
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Override
    public List<ShoppingCartsVo> selectData(Long userId) {
        List<ShoppingCartVo> shoppingCartVos = shoppingCartMapper.selectData(userId);
        return groupShoppingCartByMerchant(shoppingCartVos);
    }

    @Override
    public Integer add(ShoppingCart shoppingCart) {
        return shoppingCartMapper.insert(shoppingCart);
    }


    public List<ShoppingCartsVo> groupShoppingCartByMerchant(List<ShoppingCartVo> shoppingCartVos) {
        Map<Long, List<ShoppingCartVo>> groupedMap = new HashMap<>();

        for (ShoppingCartVo cartItem : shoppingCartVos) {
            Long merchantId = cartItem.getMerchantId();
            if (groupedMap.containsKey(merchantId)) {
                groupedMap.get(merchantId).add(cartItem);
            } else {
                List<ShoppingCartVo> cartList = new ArrayList<>();
                cartList.add(cartItem);
                groupedMap.put(merchantId, cartList);
            }
        }

        List<ShoppingCartsVo> groupedResult = new ArrayList<>();
        for (Map.Entry<Long, List<ShoppingCartVo>> entry : groupedMap.entrySet()) {
            Long merchantId = entry.getKey();
            List<ShoppingCartVo> cartList = entry.getValue();
            String merchantName = cartList.get(0).getMerchantName() != null ? cartList.get(0).getMerchantName() : String.valueOf(merchantId);
            ShoppingCartsVo shoppingCartsVo = new ShoppingCartsVo(merchantName, cartList);
            groupedResult.add(shoppingCartsVo);
        }

        return groupedResult;
    }
}
